package com.yyfax.ph.personal.message;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import static com.yyfax.ph.personal.message.MsgModel.MSG_REFRESH;


public class MsgPresenter extends Presenter<MsgModel, MsgPresenter.View> {
	private static final String TAG = MsgPresenter.class.getSimpleName();

	public static class Generator implements PresenterFactory<MsgPresenter> {
		@Override
		public MsgPresenter create() {
			return new MsgPresenter();
		}
	}

	private View mView;

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new MsgModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		void setMsgRead(boolean readFlag);

		void refreshMsgSuccess(List<MsgModel.MsgInfo> stationInfo);

		void loadMoreMsgSuccess(List<MsgModel.MsgInfo> stationInfo);

		void getMsgFailure();
	}

	//获取站内信已读状态
	public void getMsgStatus() {
		execute(null, MsgModel.MSG_CHECK_INFO, false);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getMsgStatusResult(MsgModel.MsgStatusResult msgStatusResult) {
		if (null == mView)
			return;
		if (!TextUtils.isEmpty(msgStatusResult.getStatus()) && isResponseSuccess(msgStatusResult)) {
			String content = msgStatusResult.getContent();
			if (!TextUtils.isEmpty(content)) {
				if (content.equalsIgnoreCase(MsgModel.MESSAGE_READ)) {
					mView.setMsgRead(false);
				} else if (content.equalsIgnoreCase(MsgModel.MESSAGE_UNREAD)) {
					mView.setMsgRead(true);
				}
			}
		}
	}

	//分页获取站内信消息
	public void getMsgList(int pageNo, int pageSize) {
		MsgModel.MsgParam msgParam = new MsgModel.MsgParam();
		msgParam.pageNo = String.valueOf(pageNo);
		msgParam.pageSize = String.valueOf(pageSize);
		if (pageNo > 1) {
			execute(msgParam, MsgModel.MSG_LOAD_MORE, false);
		} else {
			execute(msgParam, MSG_REFRESH, false);
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getMsgListResult(MsgModel.MsgInfoResult msgInfoResult) {
		if (null == mView)
			return;
		if (!TextUtils.isEmpty(msgInfoResult.getStatus()) && isResponseSuccess(msgInfoResult)) {
			List<MsgModel.MsgInfo> msgInfo = msgInfoResult.getContent();
			if (msgInfoResult.requestCode == MSG_REFRESH) {
				mView.refreshMsgSuccess(msgInfo);
			} else {
				mView.loadMoreMsgSuccess(msgInfo);
			}
			return;
		}
		mView.getMsgFailure();
	}
}
